package com.lancoo.znbkxx.teacher.aibkTestCoach.kBase

import android.util.SparseArray
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.PagerAdapter

/**
 * 主页ViewPager适配器
 * 用于刷新显示替换的试题
 */
class MyRefreshFragmentPagerAdapter(private val mFragmentManager: FragmentManager, //继承FragmentPagerAdapter类 ,并自定义的构造器
                              private val fragments: List<Fragment>) : FragmentPagerAdapter(mFragmentManager) {

    //保存每个Fragment的Tag，刷新页面的依据
    protected var tags: SparseArray<String> = SparseArray()

    override fun getItem(position: Int): Fragment {
        return fragments[position]
    }

    override fun getCount(): Int {
        return fragments.size
    }

    override fun getItemId(position: Int): Long {
        return fragments[position].hashCode().toLong()
    }

    override fun getItemPosition(`object`: Any): Int {
        val fragment = `object` as Fragment
        //如果Item对应的Tag存在，则不进行刷新
        return if (tags.indexOfValue(fragment.tag) > -1) {
            super.getItemPosition(`object`)
        } else PagerAdapter.POSITION_NONE
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        //得到缓存的fragment
        val fragment = super.instantiateItem(container, position) as Fragment
        val tag = fragment.tag
        //保存每个Fragment的Tag
        tags.put(position, tag)
        return fragment
    }

    //拿到指定位置的Fragment
    fun getFragmentByPosition(position: Int): Fragment? {
        return mFragmentManager.findFragmentByTag(tags.get(position))
    }

    fun getFragments(): List<Fragment> {
        return mFragmentManager.fragments
    }

    //刷新指定位置的Fragment
    fun notifyFragmentByPosition(position: Int) {
        tags.removeAt(position)
        notifyDataSetChanged()
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
//        super.destroyItem(container, position, object);
    }

    override fun notifyDataSetChanged() {
        super.notifyDataSetChanged()
    }

}